<template>
  <view class="data-detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="circle" size="40" color="#007bff"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="errorMessage" class="error-container">
      <u-empty 
        text="获取详情失败" 
        icon="error-circle"
        mode="data"
      />
      <u-button 
        type="primary" 
        text="重新加载" 
        @click="loadRepairDetail"
        class="retry-button"
      />
    </view>

    <!-- 详情内容 -->
    <view v-else-if="repairInfo" class="detail-content">
      <!-- 工单状态卡片 -->
      <view class="status-section">
        <view class="status-card">
          <view class="status-header">
            <text class="status-title">{{ repairInfo.title || repairInfo.orderNo }}</text>
            <view class="status-tag">
              <u-tag 
                :text="getStatusText(repairInfo.status)" 
                :type="getStatusType(repairInfo.status)" 
                size="mini"
              />
            </view>
          </view>
          <view class="status-desc">{{ getStatusDescription(repairInfo.status) }}</view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="info-section">
        <view class="info-card">
          <view class="card-title">基本信息</view>
          <view class="info-list">
            <view class="info-item">
              <view class="info-label">
                <u-icon name="file-text" size="16" color="#666"></u-icon>
                <text>工单编号</text>
              </view>
              <text class="info-value">{{ repairInfo.orderNo || '--' }}</text>
            </view>
            <view class="info-item">
              <view class="info-label">
                <u-icon name="calendar" size="16" color="#666"></u-icon>
                <text>创建时间</text>
              </view>
              <text class="info-value">{{ formatTime(repairInfo.createTime) }}</text>
            </view>
            <view class="info-item">
              <view class="info-label">
                <u-icon name="flag" size="16" color="#666"></u-icon>
                <text>紧急程度</text>
              </view>
              <text class="info-value" :style="{ color: getPriorityColor(repairInfo.urgencyLevel) }">
                {{ repairInfo.urgencyLevelName || '--' }}
              </text>
            </view>
            <view class="info-item">
              <view class="info-label">
                <u-icon name="account" size="16" color="#666"></u-icon>
                <text>报修人</text>
              </view>
              <text class="info-value">{{ repairInfo.reportUserName || '--' }}</text>
            </view>
            <view class="info-item">
              <view class="info-label">
                <u-icon name="phone" size="16" color="#666"></u-icon>
                <text>联系电话</text>
              </view>
              <text class="info-value">{{ repairInfo.reportUserPhone || '--' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 维修信息 -->
      <view class="detail-section">
        <view class="detail-card">
          <view class="card-title">维修信息</view>
          <view class="detail-list">
            <view class="detail-item">
              <text class="detail-label">维修地址</text>
              <text class="detail-value">{{ repairInfo.repairAddress || '--' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">问题描述</text>
              <text class="detail-value">{{ repairInfo.description || '--' }}</text>
            </view>
            <view class="detail-item" v-if="repairInfo.assignedUserName">
              <text class="detail-label">维修人员</text>
              <text class="detail-value">{{ repairInfo.assignedUserName }}</text>
            </view>
            <view class="detail-item" v-if="repairInfo.estimatedCompleteTime">
              <text class="detail-label">预计完成时间</text>
              <text class="detail-value">{{ formatTime(repairInfo.estimatedCompleteTime) }}</text>
            </view>
            <view class="detail-item" v-if="repairInfo.actualCompleteTime">
              <text class="detail-label">实际完成时间</text>
              <text class="detail-value">{{ formatTime(repairInfo.actualCompleteTime) }}</text>
            </view>
            <view class="detail-item" v-if="repairInfo.remark">
              <text class="detail-label">备注说明</text>
              <text class="detail-value">{{ repairInfo.remark }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 图片信息 -->
      <view class="image-section" v-if="repairImages && repairImages.length > 0">
        <view class="image-card">
          <view class="card-title">相关图片</view>
          <AppImagePreview 
            :images="repairImages"
            :show-image-info="true"
            empty-text="暂无图片"
            @preview="handleImagePreview"
            @error="handleImageError"
            @load="handleImageLoad"
          />
        </view>
      </view>

      <!-- 处理记录 -->
      <view class="record-section" v-if="processRecords && processRecords.length > 0">
        <view class="record-card">
          <view class="card-title">处理记录</view>
          <view class="record-list">
            <view 
              v-for="(record, index) in processRecords" 
              :key="index"
              class="record-item"
            >
              <view class="record-time">{{ formatTime(record.createTime) }}</view>
              <view class="record-content">{{ record.content }}</view>
              <view class="record-user">{{ record.operatorName }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section" v-if="canShowAction">
      <u-button 
        v-if="repairInfo?.canAssign"
        type="primary" 
        text="分配工单"
        size="large"
        @click="handleAssign"
        :loading="actionLoading"
        class="action-button"
      />
      <u-button 
        v-if="repairInfo?.canComplete"
        type="success" 
        text="完成工单"
        size="large"
        @click="handleComplete"
        :loading="actionLoading"
        class="action-button"
      />
      <u-button 
        v-if="repairInfo?.canAccept"
        type="warning" 
        text="接受工单"
        size="large"
        @click="handleAccept"
        :loading="actionLoading"
        class="action-button"
      />
    </view>
  </view>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { repairWorkApi } from '@/api/repair-work'
import AppImagePreview from '@/components/AppImagePreview.vue'

export default {
  name: 'RepairDetail',
  components: {
    AppImagePreview
  },
  setup() {
    // 响应式数据
    const repairInfo = ref(null)
    const repairImages = ref([])
    const processRecords = ref([])
    const loading = ref(false)
    const actionLoading = ref(false)
    const errorMessage = ref('')
    const repairId = ref('')

    // 计算属性
    const canShowAction = computed(() => {
      if (!repairInfo.value) return false
      return repairInfo.value.canAssign || 
             repairInfo.value.canComplete || 
             repairInfo.value.canAccept
    })

    // 状态判断函数
    const getStatusText = (status) => {
      const statusMap = {
        1: '待处理',
        2: '进行中',
        3: '维修中',
        4: '已完成',
        5: '已取消'
      }
      return statusMap[status] || '未知状态'
    }

    const getStatusType = (status) => {
      const typeMap = {
        1: 'warning',
        2: 'info',
        3: 'primary',
        4: 'success',
        5: 'error'
      }
      return typeMap[status] || 'info'
    }

    const getStatusDescription = (status) => {
      const descMap = {
        1: '工单已创建，等待分配维修人员',
        2: '工单已分配，等待维修人员接受',
        3: '维修人员已接受，正在维修中',
        4: '维修已完成，等待确认',
        5: '工单已取消'
      }
      return descMap[status] || '状态描述未知'
    }

    const getPriorityColor = (urgencyLevel) => {
      const colorMap = {
        1: '#999999',  // 一般
        2: '#ff9500',  // 紧急
        3: '#ff4757'   // 非常紧急
      }
      return colorMap[urgencyLevel] || '#999999'
    }

    // 时间格式化
    const formatTime = (time) => {
      if (!time) return '--'
      const date = new Date(time)
      return date.toLocaleString('zh-CN')
    }

    // 数据加载
    const loadRepairDetail = async () => {
      if (!repairId.value) {
        errorMessage.value = '工单ID不能为空'
        return
      }

      try {
        loading.value = true
        errorMessage.value = ''
        
        const response = await repairWorkApi.getRepairDetail(repairId.value)
        if (response.code === 200 && response.data) {
          repairInfo.value = response.data
          
          // 处理图片数据
          if (response.data.images && response.data.images.length > 0) {
            repairImages.value = response.data.images.map(img => ({
              id: img.id,
              fileUrl: img.fileUrl,
              fileName: img.fileName || '图片',
              fileSize: img.fileSize || 0
            }))
          }
          
          // 处理记录数据
          if (response.data.processRecords && response.data.processRecords.length > 0) {
            processRecords.value = response.data.processRecords
          }
          
          console.log('维修详情加载成功:', response.data)
        } else {
          errorMessage.value = response.message || '获取详情失败'
        }
      } catch (error) {
        console.error('加载维修详情失败:', error)
        errorMessage.value = error.message || '网络错误，请重试'
      } finally {
        loading.value = false
      }
    }

    // 操作处理
    const handleAssign = () => {
      uni.navigateTo({
        url: `/pages/property-work/repair-assign?id=${repairId.value}`
      })
    }

    const handleComplete = () => {
      uni.showModal({
        title: '确认完成',
        content: '确认完成此维修工单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              actionLoading.value = true
              const response = await repairWorkApi.completeRepair(repairId.value)
              if (response.code === 200) {
                uni.showToast({ title: '工单已完成', icon: 'success' })
                // 重新加载详情
                loadRepairDetail()
              } else {
                uni.showToast({ title: response.message || '操作失败', icon: 'none' })
              }
            } catch (error) {
              console.error('完成工单失败:', error)
              uni.showToast({ title: '操作失败，请重试', icon: 'none' })
            } finally {
              actionLoading.value = false
            }
          }
        }
      })
    }

    const handleAccept = () => {
      uni.showModal({
        title: '确认接受',
        content: '确认接受此维修工单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              actionLoading.value = true
              const response = await repairWorkApi.acceptRepair(repairId.value)
              if (response.code === 200) {
                uni.showToast({ title: '工单已接受', icon: 'success' })
                // 重新加载详情
                loadRepairDetail()
              } else {
                uni.showToast({ title: response.message || '操作失败', icon: 'none' })
              }
            } catch (error) {
              console.error('接受工单失败:', error)
              uni.showToast({ title: '操作失败，请重试', icon: 'none' })
            } finally {
              actionLoading.value = false
            }
          }
        }
      })
    }

    // 图片预览事件处理
    const handleImagePreview = (data) => {
      console.log('图片预览事件:', data)
    }

    const handleImageError = (data) => {
      console.error('图片错误事件:', data)
    }

    const handleImageLoad = (data) => {
      console.log('图片加载事件:', data)
    }

    // 生命周期
    onMounted(() => {
      // 获取页面参数
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      repairId.value = currentPage.options.id
      
      if (repairId.value) {
        loadRepairDetail()
      } else {
        errorMessage.value = '工单ID不能为空'
      }
    })

    return {
      repairInfo,
      repairImages,
      processRecords,
      loading,
      actionLoading,
      errorMessage,
      canShowAction,
      getStatusText,
      getStatusType,
      getStatusDescription,
      getPriorityColor,
      formatTime,
      loadRepairDetail,
      handleAssign,
      handleComplete,
      handleAccept,
      handleImagePreview,
      handleImageError,
      handleImageLoad
    }
  }
}
</script>

<style lang="scss" scoped>
.data-detail-page {
  min-height: 100vh;
  width: 100%;
  background: #f5f5f5;
  padding-bottom: 120rpx;
  box-sizing: border-box;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  
  .loading-text {
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #666;
  }
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  
  .retry-button {
    margin-top: 30rpx;
  }
}

.detail-content {
  width: 100%;
  box-sizing: border-box;
}

.status-section, .info-section, .detail-section, .image-section, .record-section {
  padding: 0 20rpx 20rpx;
  width: 100%;
  box-sizing: border-box;
}

.status-card, .info-card, .detail-card, .image-card, .record-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  width: 100%;
  box-sizing: border-box;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .card-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.status-card {
  .status-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    
    .status-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      flex: 1;
      margin-right: 20rpx;
    }
  }
  
  .status-desc {
    font-size: 26rpx;
    color: #666;
    line-height: 1.4;
  }
}

.info-list, .detail-list {
  .info-item, .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f8f8f8;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label {
      display: flex;
      align-items: center;
      gap: 12rpx;
      flex-shrink: 0;
      width: 160rpx;
      
      text {
        font-size: 26rpx;
        color: #666;
      }
    }
    
    .info-value, .detail-value {
      font-size: 26rpx;
      color: #333;
      text-align: right;
      flex: 1;
      word-break: break-all;
    }
    
    .detail-label {
      font-size: 26rpx;
      color: #666;
    }
    
    .detail-value {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.record-list {
  .record-item {
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f8f8f8;
    
    &:last-child {
      border-bottom: none;
    }
    
    .record-time {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 8rpx;
    }
    
    .record-content {
      font-size: 26rpx;
      color: #333;
      line-height: 1.4;
      margin-bottom: 8rpx;
    }
    
    .record-user {
      font-size: 24rpx;
      color: #666;
      text-align: right;
    }
  }
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  background: white;
  padding: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
  box-sizing: border-box;
  
  .action-button {
    width: 100%;
    margin-bottom: 10rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .status-section, .info-section, .detail-section, .image-section, .record-section {
    padding: 0 15rpx 15rpx;
  }
  
  .status-card, .info-card, .detail-card, .image-card, .record-card {
    padding: 20rpx;
  }
}

@media screen and (min-width: 769px) {
  .data-detail-page {
    max-width: 800px;
    margin: 0 auto;
  }
}
</style>
